package com.sy.core.web.system;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.core.model.SysMenu;
import com.sy.core.model.common.Tree;
import com.sy.core.service.SysMenuService;
import com.sy.core.util.BaseUUID;
import com.sy.core.util.RestResult;
import com.sy.core.web.BaseCtl;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ResponseBody;


import com.sy.core.model.SysRole;
import com.sy.core.service.SysRoleService;




/**
 * 	TODO 请用一句话描述该类的作用
 * @author CaiXinChong email:1060296473@qq.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/sysRole")
public class SysRoleCtl extends BaseCtl {

    @Autowired
    private SysRoleService  sysRoleService;
    

	@RequestMapping("/{path}")
	public ModelAndView toAnyPage(@PathVariable String path,ModelAndView mv){
	    mv.setViewName(path);
	    return mv;
    }
    
    /**
     * Action for Add
     */
    @RequestMapping(value = "/save",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult save(SysRole sysRole,String jsonstr){
        sysRole = JSONObject.parseObject(jsonstr,SysRole.class);
        String pk = sysRole.getPk();
        RestResult rr = null;
        try {
            if(pk==null||pk.equals("")){
                pk = BaseUUID.getUUID();
                sysRole.setPk(pk);
                sysRoleService.insert(sysRole);
            }else{
                sysRoleService.update(sysRole);
            }
            rr=new RestResult("200","SUCCESS",pk);
        } catch (Exception e) {
            e.printStackTrace();
            rr = new RestResult("201","FAILED");
        }
        return rr;
    }

    /**
     * Action for update
     */
    @RequestMapping(value = "/update",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult update(SysRole sysRole){
        RestResult rr = null;
        try {
        sysRoleService.update(sysRole);
        rr=new RestResult("200","SUCCESS");
        } catch (Exception e) {
        e.printStackTrace();
        rr = new RestResult("201","FAILED");
        }
        return rr;
    }
    
    /**
     * Action for SelectOneByKey
     */
    @RequestMapping(value = "/query/{key}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult queryByPrimaryKey(@PathVariable String key){
       try{
            SysRole sysRole = sysRoleService.queryByPrimaryKey(key);
      	 	return new RestResult("200","SUCCESS",sysRole);
       }catch(Exception e){
    	   	logger.error("Query Model SysRole By PrimaryKey Is Fail:"+e.getMessage());
       }
       		return new RestResult("201","FAIL");
    }
    
    /**
     * Action for SelectList
     */
    @RequestMapping(value = "/list",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult queryList(String str,SysRole sysRole){
        sysRole = JSONObject.parseObject(str,SysRole.class);
        JSONObject json = JSONObject.parseObject(str);
       try{
           PageHelper.startPage(Integer.parseInt(json.getString("currentPage")),Integer.parseInt(json.getString("pageSize")));
      		List<SysRole> sysRoleList = sysRoleService.queryByCondition(sysRole);
           PageInfo<SysRole> info = new PageInfo<>(sysRoleList);
      	 	return new RestResult("200","SUCCESS",info);
       }catch(Exception e){
    	   logger.error("Query Model SysRole List Fail :"+e.getMessage());
    	   return new RestResult("201","FAIL");
       }
    }
    
    /**
     * Action for DeleteModel
     */
    @RequestMapping("/delete/{pks}")
    @ResponseBody
    public RestResult delete(@PathVariable String pks){
        RestResult rr = null;
        try {
        sysRoleService.delete(pks);
        rr=new RestResult("200","SUCCESS");
        } catch (Exception e) {
        e.printStackTrace();
        rr = new RestResult("201","FAILED");
        }
        return rr;
    }

    /**
     * 查询菜单树
     */
    @GetMapping("getMenuTree")
    @ResponseBody
    public RestResult getMenuTree(SysMenu sysMenu){
        RestResult rr = null;
        //查询出所有的一级菜单[pcode=0为一级菜单]
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            List<SysMenu> sysMenuList = sysMenuService.queryByCondition(sysMenu);
            if (sysMenuList.size() > 0) {
                for (SysMenu menu : sysMenuList) {
                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("pk", menu.getPk());
                    map.put("label", menu.getName());
                    sysMenu.setPcode(menu.getPk());
                    map.put("children", getChildren(sysMenu));
                    list.add(map);
                }
            }
            rr = new RestResult("200","success",list);
        }catch (Exception e){
            logger.error("failed",e);
            rr=new RestResult("201","Failed");
        }
        return rr;
    }

    /**
     * 递归
     *
     * @return
     */
    public List<Map<String, Object>> getChildren(SysMenu sysMenu) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<SysMenu> sysMenuList = sysMenuService.queryByCondition(sysMenu);
        if(sysMenuList.size()>0){
            for (SysMenu menu : sysMenuList) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("pk", menu.getPk());
                map.put("label", menu.getName());
                sysMenu.setPcode(menu.getPk());
                map.put("children", getChildren(sysMenu));
                list.add(map);
            }
        }
        return list;
    }
}
